package it.com.chen.movieReleasesDB;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

public abstract class OnlineDBReader {

	private static HashMap<Integer, DBEntry> DB = new HashMap<>();

	public static HashMap<Integer, DBEntry> populateDB(String pageMonth,
			int pageYear, HashMap<Integer, DBEntry> db, Calendar lastUpdate) {

		String htmlSourceLink = "http://www.movieinsider.com/blu-rays/"
				+ pageMonth + "/"
				+ pageYear + "/";
		
		Calendar today = Calendar.getInstance();
		
		System.out.println("# Reading the html source \""+htmlSourceLink+"\"");
		System.out.println("Today is \"" + today.get(Calendar.DAY_OF_MONTH)
				+ "/" + CalendarMonthManager.convertMonth(today.get(Calendar.MONTH)) + "/"
				+ today.get(Calendar.YEAR)
				+ "\" and the last update was on day \""
				+ lastUpdate.get(Calendar.DAY_OF_MONTH) + "/"
				+ CalendarMonthManager.convertMonth(lastUpdate.get(Calendar.MONTH)) + "/"
				+ lastUpdate.get(Calendar.YEAR) + "\"");

		Document doc;
		try {
			doc = Jsoup.connect(htmlSourceLink).get();

			Element body = doc.body();
			Element main = body.getElementById("main");
			Element section = main.getElementById("section");

			Elements childs = section.getAllElements();
			Iterator<Element> childsIterator = childs.iterator();

			Calendar releaseDate = Calendar.getInstance();

			while (childsIterator.hasNext()) {
				Element child = childsIterator.next();
				if (child.nodeName().equals("h3")) {
					Elements dateEntry = child.getElementsByTag("a");
					String link = dateEntry.attr("href");
					Scanner linkScanner = new Scanner(link);
					linkScanner.useDelimiter("\\/");
					HashMap<Integer, String> separatedParts = new HashMap<>();
					int counter = 0;
					while (linkScanner.hasNext()) {
						separatedParts.put(counter, linkScanner.next());
						counter++;
					}
					String monthString = separatedParts.get(separatedParts
							.size() - 3);
					
					int month = CalendarMonthManager.convertMonth(monthString);
					int year = Integer.parseInt(separatedParts
							.get(separatedParts.size() - 2));
					int date = Integer.parseInt(separatedParts
							.get(separatedParts.size() - 1));
					
					releaseDate.set(year, month, date);

					System.out.println("\tRelease date set to \""
							+ releaseDate.get(Calendar.DAY_OF_MONTH) + "/"
							+ CalendarMonthManager.convertMonth(releaseDate.get(Calendar.MONTH)) + "/"
							+ releaseDate.get(Calendar.YEAR) + " from link \""
							+ link+"\"");
				}

				int dbCounter = db.size();

				if (releaseDate.after(lastUpdate) && releaseDate.before(today)) {

					if (child.nodeName().equals("ul") && child.hasAttr("class")) {
						Attributes attributes = child.attributes();
						for (Attribute attribute : attributes) {
							if (attribute.getValue().equals("monthlyDIV")) {
								List<Element> movieEntries = child.children();
								for (Element entry : movieEntries) {
									Element linkEntry = entry.child(0);
									String descriptionUrl = linkEntry
											.attr("href");
									String movieTitle = linkEntry.text();

									DBEntry dbEntry = new DBEntry(releaseDate.get(Calendar.DAY_OF_MONTH),releaseDate.get(Calendar.MONTH),releaseDate.get(Calendar.YEAR),
											movieTitle, descriptionUrl);

									db.put(dbCounter, dbEntry);
									dbCounter++;
									
									System.out.println("\t\tRead movie \""
											+ dbEntry.getMovieTitle() + "\" with link \""
											+ dbEntry.getDescriptionUrl()+"\" and with release date set to \""+dbEntry.getReleaseDate()
											+ "/" + CalendarMonthManager.convertMonth(dbEntry.getReleaseMonth())
											+ "/" + dbEntry.getReleaseYear()+"\"");
								}
							}
						}
					}

				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return db;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Calendar lastUpdate = Calendar.getInstance();
		lastUpdate.set(2012, 9, 16);
		HashMap<Integer, DBEntry> db = new HashMap<>();
		db = populateDB("october", 2012, db, lastUpdate);
		System.out.println("\n");
		MovieListPrinter.print(db);
	}

}
